package cn.bugDance.infrastructure.persistent.repository;

import cn.bugDance.domain.award.model.entity.TaskEntity;
import cn.bugDance.domain.award.model.valobj.SendAwardVO;
import cn.bugDance.domain.award.model.valobj.TaskStateVO;
import cn.bugDance.domain.task.event.SendAwardEvent;
import cn.bugDance.domain.task.repository.ITaskRepository;
import cn.bugDance.infrastructure.event.EventPublisher;
import cn.bugDance.infrastructure.persistent.dao.ITaskDao;
import cn.bugDance.infrastructure.persistent.po.Task;
import cn.bugDance.types.response.BaseEvent;
import cn.bugstack.middleware.db.router.strategy.IDBRouterStrategy;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ThreadPoolExecutor;

@Repository
@Slf4j
public class TaskRepository implements ITaskRepository {

    @Resource
    private ITaskDao taskDao;
    @Resource
    private EventPublisher eventPublisher;
    @Resource
    private IDBRouterStrategy dbRouter;


    @Override
    public List<TaskEntity> queryNoCompletedTask() {
        List<Task> tasks = taskDao.getNoCompletedTask();

        if(tasks == null || tasks.isEmpty()){
            return null;
        }

        List<TaskEntity> taskEntities = new ArrayList<>();
        for (Task task : tasks) {
            TaskEntity taskEntity = new TaskEntity();

            taskEntity.setUserId(task.getUserId());
            taskEntity.setState(TaskStateVO.valueOf(task.getState()));
            taskEntity.setTopic(task.getTopic());
            BaseEvent<SendAwardVO> message = JSON.parseObject(task.getMessage(), new TypeReference<BaseEvent<SendAwardVO>>(){});
            taskEntity.setMessage(message);

            taskEntities.add(taskEntity);
        }
        return taskEntities;
    }

    @Override
    public void sendAward(TaskEntity taskEntity) {
        eventPublisher.publish(taskEntity.getTopic(), taskEntity.getMessage());
    }

    @Override
    public void updateTaskStateSuccess(String messageId) {
        taskDao.updateTaskStateSuccess(messageId);
    }

    @Override
    public void updateTaskStateFail(String messageId) {
        taskDao.updateTaskStateFail(messageId);
    }
}
